package com.briup.sxau.service.impl;

import com.briup.sxau.bean.User;
import com.briup.sxau.dao.IUserRepository;
import com.briup.sxau.service.IUserService;
import com.briup.sxau.util.SxauException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserRepository userRepository;
    @Override
    public String login(String username, String password) {
//        根据用户名去判断用户是否存在
        User user = userRepository.findByUsername(username);

        if (Objects.isNull(user)){
            throw  new SxauException("用户不存在");
        }else {
//            输入的密码和数据的密码去比较 看值是否相等
            if (password.equals(user.getPassword())){
//获取系统时间戳
                long millis = System.currentTimeMillis();
                long expir=1000*60*60;
                String token = Jwts.builder()
                        .setId(UUID.randomUUID().toString())
                        .setSubject(username)
                        .setIssuedAt(new Date(millis))
                        .setExpiration(new Date(millis + expir))
                        .signWith(SignatureAlgorithm.HS256, "shitongtong")
                        .compact();
                return token;
            }else {
                throw  new SxauException("用户名密码错误");
            }
        }

    }
}
